package com.brotherly.util.downloader;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.IBinder;
import android.util.Log;

public class DownLoaderSerivce extends Service {

    private DownLoaderThread theard;

    @Override
    public IBinder onBind(Intent arg0)
    {
        return null;
    }

    @Override
    public void onCreate()
    {
        super.onCreate();
        theard = new DownLoaderThread();
        theard.start();

        IntentFilter mFilter = new IntentFilter();
        mFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(mReceiver, mFilter);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId)
    {
        int result = super.onStartCommand(intent, flags, startId);
        // if (!theard.isAlive())
        // {
        // theard = new DownLoaderThread();
        // theard.start();
        // }
        return result;
    }

    @Override
    public void onDestroy()
    {
        super.onDestroy();
    }

    class DownLoaderThread extends Thread
    {
        @Override
        public void run()
        {
            // while (true)
            {
                try
                {
                    // DownLoaderUtil.getInstence(DownLoaderSerivce.this).pauseDownloadAll();
                    // DownLoaderUtil.getInstence(DownLoaderSerivce.this).downLoaderWatcher();
                    // Thread.sleep(60 * 1000 * 30);
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
        }
    }

    private BroadcastReceiver mReceiver = new BroadcastReceiver()
    {
        @Override
        public void onReceive(Context context, Intent intent)
        {
            String action = intent.getAction();
            if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION))
            {
                Log.d("mark", "网络状态已经改变");
                ConnectivityManager connectivityManager = (ConnectivityManager)

                        getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo info = connectivityManager.getActiveNetworkInfo();
                if (info != null && info.isAvailable())
                {
                    Intent i = new Intent(DownLoaderSerivce.this, DownLoaderSerivce.class);
                    startService(i);
                }
            }
        }
    };
}
